package com.cqyc.shop.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqyc.shop.comm.JdbcUtils;
import com.cqyc.shop.comm.commException;
import com.cqyc.shop.domain.User;

public class UserDao {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public User rowmap(ResultSet rs) throws SQLException {
		User user = new User();
		user.setId(rs.getInt("id"));
		user.setUsercode(rs.getString("usercode"));
		user.setUsername("username");
		user.setPassword(rs.getString("password"));
		user.setBrithday(rs.getDate("birthday"));
		user.setEamil(rs.getString("email"));
		user.setPhone(rs.getString("phone"));
		user.setSex(rs.getInt("sex"));
		user.setUsertype(rs.getInt("usertypr"));
		return user;
	}
	/**
	 * 查找用户，实现登录
	 * @param usercode
	 * @param password
	 * @return
	 */
	public User findcode(String usercode) {
		Connection conn=null;
		PreparedStatement ps =null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnerction();
			String sql="select * from user where usercode=? ";
			ps = conn.prepareStatement(sql);
			ps.setString(1,usercode);
			rs = ps.executeQuery();
			while (rs.next()) {
				return rowmap(rs);
			}
			logger.debug("查询成功");
		} catch (Exception e) {
			logger.error("查询异常：{}",e.getMessage());
			throw new commException("数据查询失败");
		}finally {
			JdbcUtils.close(conn, ps, rs);
		}
		
		return null;
	}

	/**
	 * 注册用户
	 * @param user
	 */
	public void save(User user) {
		Connection conn=null;
		PreparedStatement ps =null;
		ResultSet rs = null;
		
		try {
			conn = JdbcUtils.getConnerction();
			String sql="insert into user(usercode,username,password,birthday,email,phone,sex,usertypr) values(?,?,?,?,?,?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUsercode());
			ps.setString(2,user.getUsername());
			ps.setString(3, user.getPassword());
			ps.setDate(4,  new java.sql.Date(user.getBrithday().getTime()) );
			ps.setString(5,user.getEamil());
			ps.setString(6, user.getPhone());
			ps.setInt(7,user.getSex());
			ps.setInt(8, user.getUsertype());
			int ret = ps.executeUpdate();
			if(ret<0) {
				throw new commException("数据插入失败");
			}
			logger.debug("数据插入成功");
		} catch (Exception e) {
			logger.error("{}",e.getMessage());
			throw new commException("数据插入异常");
		}finally {
			JdbcUtils.close(conn, ps, rs);
		}
	}
		
}
